﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Liolikas.LiolikasGame;
using System.IO;
using Liolikas.GameMenu;
using System.Security.AccessControl;

namespace Liolikas.Scores
{
    class HighScore
    {
        public List<Score> scoreList {get;set;}
        static private HighScore highScore;
        static String HIGHSCORES_FILE="scores.dat";
        string appDataPath;
        string fullDataPath;
        static int NUMBER_OF_HIGHSCORES = 5;
        HighScore()
        {
            scoreList = new List<Score>();
            appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            fullDataPath = appDataPath + "\\" + HIGHSCORES_FILE;
            if (File.Exists(fullDataPath)) LoadScoreData();
        }
        public static HighScore GetHightScore()
        {
            if (highScore == null) highScore = new HighScore();
            return highScore;
        }

        private Boolean isHighScore(int score){
            if (scoreList.Count < NUMBER_OF_HIGHSCORES)
                return true;
            else if (scoreList.Last().points < score)
                return true;
            else return false;
        }

        private void AddHighScore(Score score){

            scoreList.Add(score);
            scoreList = (from entry in scoreList orderby entry.points descending select entry).Take(NUMBER_OF_HIGHSCORES).ToList();
            StoreScoreData();   
           
        }
        public Boolean NewScore(int score, String data)
        {
            if (isHighScore(score))
            {
                AddHighScore(new Score (score, data));
                return true;
            }
            else
            {
                return false;
            }

        }
        private void StoreScoreData()
        {

            StreamWriter writer = new StreamWriter(fullDataPath, false);
            foreach (Score score in scoreList) score.saveData(writer);
            writer.Close();
        }
        private void LoadScoreData()
        {
            String line;
            if (File.Exists(fullDataPath))
            {
                StreamReader highScoreFile = new StreamReader(fullDataPath);
                while ((line = highScoreFile.ReadLine()) != null)
                {
                    Score loadedScore = Score.LoadScore(line);
                    if (loadedScore!=null) scoreList.Add(loadedScore);
                }

                highScoreFile.Close();
            }
        }

        public void ShowHighScore()
        {
            Renderer.ShowHighScore();
            Console.ReadLine();
            Menu.GetMenu().ShowMenu();
        }
       
    }
}
